package tank;

import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

/**
 * @Auther: xiaofei
 * @Date: 2021/6/9 - 06 - 09 - 14:20
 * @Description: tank
 * @version: 1.0
 */
public class TankFrame extends Frame {

    Tank myTank = new Tank(200,200,Dir.DOWN);
    //建立一个框架界面
    public TankFrame(){
        setSize(800,600);
        setResizable(false);
        setTitle("Tank War");
        setVisible(true);
        //键盘监听处理
        this.addKeyListener(new MyKeyListener());

        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }

    @Override
    //在框中画内容
    public void paint(Graphics g){
        myTank.paint(g);
        }

    //键盘监听处理类
    class MyKeyListener extends KeyAdapter{
        boolean bL = false;
        boolean bU = false;
        boolean bR = false;
        boolean bD = false;
        @Override
        //添加键盘处理，根据上下左右键来判定坦克的方向
        public void keyPressed(KeyEvent e) {
            int key = e.getKeyCode();
            switch (key){
                case KeyEvent.VK_LEFT:
                    bL = true;
                    //x -= 10;
                    break;
                case KeyEvent.VK_UP:
                    bU = true;
                    //y -= 10;
                    break;
                case KeyEvent.VK_RIGHT:
                    bR = true;
                    //x += 10;
                    break;
                case KeyEvent.VK_DOWN:
                    bD = true;
                    //y += 10;
                    break;
                default:
                    break;
            }
            setMaintankDir();
            repaint();
        }

        @Override
        public void keyReleased(KeyEvent e) {
            int key = e.getKeyCode();
            switch (key){
                case KeyEvent.VK_LEFT:
                    bL = false;
                    break;
                case KeyEvent.VK_UP:
                    bU = false;
                    break;
                case KeyEvent.VK_RIGHT:
                    bR = false;
                    break;
                case KeyEvent.VK_DOWN:
                    bD = false;
                    break;
                default:
                    break;
            }
            setMaintankDir();
        }
        //根据按键状态改变坦克方向
        private void setMaintankDir() {
            if(bL) myTank.setDir(Dir.LEFT);
            if(bU) myTank.setDir(Dir.UP);
            if(bR) myTank.setDir(Dir.RIGHT);
            if(bD) myTank.setDir(Dir.DOWN);
        }
    }

}
